package com.yuncommunity.chess;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import chessweb.Chessweb;

public class MainActivity extends AppCompatActivity {
    private String targetBasePath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String appConf = appConf();
        ((TextView) findViewById(R.id.textView)).setText("启动成功..." + "\n" +
                "IP: " + getIpAddress() + "\n" +
                appConf);

        final String url = "http://" + getIpAddress() + ":8048";
        findViewById(R.id.open_browser).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
            }
        });

        findViewById(R.id.share_link).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            }
        });

        targetBasePath = getFilesDir().getAbsolutePath() + "/";
        if (文件不同(appConf)) // 判断文件是否已经复制过
            copyFileOrDir(""); // 从 assets 复制到 内置存储中

        new Thread() {
            @Override
            public void run() {
                super.run();
                Chessweb.run(getFilesDir().getAbsolutePath());
            }
        }.start();
    }

    private boolean 文件不同(String appConf) {
        File file = new File(targetBasePath + "conf/app.conf");
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String mLine;
            while ((mLine = reader.readLine()) != null) {
                sb.append(mLine + "\n");
            }
        } catch (IOException e) {
            showLog(e.toString());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    showLog(e.toString());
                }
            }
        }
        return !sb.toString().equals(appConf);
    }

    private void showLog(String log) {
        Log.d("oldfeel", log);
    }

    private void copyFileOrDir(String path) {
        AssetManager assetManager = this.getAssets();
        String assets[] = null;
        try {
            assets = assetManager.list(path);
            if (assets.length == 0) {
                copyFile(path);
            } else {
                String fullPath = targetBasePath + path;
                File dir = new File(fullPath);
                if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                    if (!dir.mkdirs())
                        showLog("could not create dir " + fullPath);
                for (int i = 0; i < assets.length; ++i) {
                    String p;
                    if (path.equals(""))
                        p = "";
                    else
                        p = path + "/";
                    if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                        copyFileOrDir(p + assets[i]);
                }
            }
        } catch (IOException ex) {
            showLog("I/O Exception" + ex);
        }
    }

    private void copyFile(String filename) {
        AssetManager assetManager = this.getAssets();

        InputStream in = null;
        OutputStream out = null;
        String newFileName = null;
        try {
            in = assetManager.open(filename);
            if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
                newFileName = targetBasePath + filename.substring(0, filename.length() - 4);
            else
                newFileName = targetBasePath + filename;
            out = new FileOutputStream(newFileName);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e) {
            showLog("Exception in copyFile() of " + newFileName);
            showLog("Exception in copyFile() " + e.toString());
        }

    }

    private String appConf() {
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(getAssets().open("conf/app.conf")));
            String mLine;
            while ((mLine = reader.readLine()) != null) {
                sb.append(mLine + "\n");
            }
        } catch (IOException e) {
            showLog(e.toString());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    showLog(e.toString());
                }
            }
        }
        return sb.toString();
    }

    private String getIpAddress() {
        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wm.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            WifiInfo info = wm.getConnectionInfo();
            int hostip = info.getIpAddress();
            String ip = (hostip & 0xFF) + "." + ((hostip >> 8) & 0xFF) + "." + ((hostip >> 16) & 0xFF) + "." + ((hostip >> 24) & 0xFF);
            return ip;
        }
        return null;
    }
}
